"use client";

import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Trash2 } from "lucide-react";
import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "@/components/ui/accordion";
import { useLanguage } from "@/contexts/LanguageContext";
import Papa from "papaparse";

interface Skill {
  id: string;
  name: string;
}

interface Course {
  id: string;
  name: string;
  skills: Skill[];
}

export function SkillList() {
  const { t } = useLanguage();
  const [courses, setCourses] = useState<Course[]>([]);
  const [newCourseName, setNewCourseName] = useState("");
  const [newSkillName, setNewSkillName] = useState("");
  const [selectedCourseId, setSelectedCourseId] = useState<string | null>(null);

  useEffect(() => {
    const savedCourses = JSON.parse(localStorage.getItem("courses") || "[]");
    if (savedCourses.length > 0) {
      setCourses(savedCourses);
    } else {
      const initialCourses: Course[] = [
        {
          id: "1",
          name: "ADST",
          skills: [
            {
              id: "adst1",
              name: "ADST 4.1.2.3 Identify the main objective for the design and any constraints",
            },
            {
              id: "adst2",
              name: "ADST 4.1.3.1 Generate potential ideas and add to others' ideas",
            },
            {
              id: "adst3",
              name: "ADST 4.1.3.2 Screen ideas against the objective and constraints",
            },
            {
              id: "adst4",
              name: "ADST 4.1.4.1 Outline a general plan, identifying tools and materials",
            },
            {
              id: "adst5",
              name: "ADST 4.1.4.2 Construct a first version of the product, making changes to tools, materials, and procedures as needed",
            },
          ],
        },
        {
          id: "2",
          name: "ART",
          skills: [
            {
              id: "art1",
              name: "ART 4.1.2 Create artistic works collaboratively and as an individual using ideas inspired by imagination, inquiry, experimentation, and purposeful play",
            },
            {
              id: "art2",
              name: "ART 4.2.2 Develop and refine ideas, processes, and technical skills in a variety of art forms to improve the quality of artistic creations",
            },
            {
              id: "art3",
              name: "ART 4.2.4 Connect knowledge and skills from other areas of learning in planning, creating, interpreting, and analyzing works for art",
            },
          ],
        },
      ];
      setCourses(initialCourses);
      localStorage.setItem("courses", JSON.stringify(initialCourses));
    }
  }, []);

  const saveCourses = (updatedCourses: Course[]) => {
    setCourses(updatedCourses);
    localStorage.setItem("courses", JSON.stringify(updatedCourses));
  };

  const addCourse = () => {
    if (newCourseName.trim()) {
      const newCourse: Course = {
        id: Date.now().toString(),
        name: newCourseName.trim(),
        skills: [],
      };
      saveCourses([...courses, newCourse]);
      setNewCourseName("");
    }
  };

  const addSkill = () => {
    if (newSkillName.trim() && selectedCourseId) {
      const updatedCourses = courses.map((course) => {
        if (course.id === selectedCourseId) {
          return {
            ...course,
            skills: [
              ...course.skills,
              { id: Date.now().toString(), name: newSkillName.trim() },
            ],
          };
        }
        return course;
      });
      saveCourses(updatedCourses);
      setNewSkillName("");
    }
  };

  const deleteCourse = (courseId: string) => {
    const updatedCourses = courses.filter((course) => course.id !== courseId);
    saveCourses(updatedCourses);
  };

  const deleteSkill = (courseId: string, skillId: string) => {
    const updatedCourses = courses.map((course) => {
      if (course.id === courseId) {
        return {
          ...course,
          skills: course.skills.filter((skill) => skill.id !== skillId),
        };
      }
      return course;
    });
    saveCourses(updatedCourses);
  };

  const exportToCSV = () => {
    const csvData = courses.flatMap((course) =>
      course.skills.map((skill) => ({
        CourseId: course.id,
        CourseName: course.name,
        SkillId: skill.id,
        SkillName: skill.name,
      }))
    );

    const csv = Papa.unparse(csvData);
    const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
    const link = document.createElement("a");
    if (link.download !== undefined) {
      const url = URL.createObjectURL(blob);
      link.setAttribute("href", url);
      link.setAttribute("download", "skill_list.csv");
      link.style.visibility = "hidden";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  };

  const importFromCSV = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      Papa.parse(file, {
        complete: (results) => {
          const importedData = results.data as {
            CourseId: string;
            CourseName: string;
            SkillId: string;
            SkillName: string;
          }[];
          const newCourses: Course[] = [];

          importedData.forEach((row) => {
            let course = newCourses.find((c) => c.id === row.CourseId);
            if (!course) {
              course = { id: row.CourseId, name: row.CourseName, skills: [] };
              newCourses.push(course);
            }
            course.skills.push({ id: row.SkillId, name: row.SkillName });
          });

          saveCourses(newCourses);
        },
        header: true,
      });
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex justify-end space-x-2 mb-4">
        <Button onClick={exportToCSV}>{t("导出CSV")}</Button>
        <label htmlFor="import-file" className="cursor-pointer">
          <Input
            id="import-file"
            type="file"
            className="hidden"
            onChange={importFromCSV}
            accept=".csv"
          />
          <Button>{t("导入CSV")}</Button>
        </label>
      </div>
      <h2 className="text-2xl font-bold">{t("技能列表")}</h2>
      <div className="space-y-2">
        <Input
          type="text"
          value={newCourseName}
          onChange={(e) => setNewCourseName(e.target.value)}
          placeholder={t("输入新课程名称")}
        />
        <Button onClick={addCourse}>{t("添加课程")}</Button>
      </div>
      <Accordion type="single" collapsible className="w-full">
        {courses.map((course) => (
          <AccordionItem key={course.id} value={course.id}>
            <AccordionTrigger className="text-left">
              <div className="flex justify-between items-center w-full">
                <span>{course.name}</span>
                <Button
                  variant="ghost"
                  size="icon"
                  onClick={(e) => {
                    e.stopPropagation();
                    deleteCourse(course.id);
                  }}
                >
                  <Trash2 className="h-4 w-4" />
                </Button>
              </div>
            </AccordionTrigger>
            <AccordionContent>
              <div className="space-y-2 mt-2">
                <Input
                  type="text"
                  value={newSkillName}
                  onChange={(e) => setNewSkillName(e.target.value)}
                  placeholder={t("输入新技能名称")}
                  onFocus={() => setSelectedCourseId(course.id)}
                />
                <Button onClick={addSkill}>{t("添加技能")}</Button>
              </div>
              <ul className="mt-2 space-y-2">
                {course.skills.map((skill) => (
                  <li
                    key={skill.id}
                    className="flex justify-between items-center bg-white p-2 rounded"
                  >
                    <span>{skill.name}</span>
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={() => deleteSkill(course.id, skill.id)}
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </li>
                ))}
              </ul>
            </AccordionContent>
          </AccordionItem>
        ))}
      </Accordion>
    </div>
  );
}
